HEX
Server: Apache/2.4.58 (Ubuntu)
System: Linux ip-172-26-0-120 6.17.0-1009-aws #9~24.04.2-Ubuntu SMP Fri Mar 6 23:50:29 UTC 2026 x86_64
User: ubuntu (1000)
PHP: 8.3.6
Disabled: NONE
Upload Files
File: /var/www/html/dashboard.orbiwheels.com/vendor/cuyz/valinor/src/Mapper/TypeTreeMapper.php
<?php

declare(strict_types=1);

namespace CuyZ\Valinor\Mapper;

use CuyZ\Valinor\Mapper\Exception\InvalidMappingTypeSignature;
use CuyZ\Valinor\Mapper\Exception\TypeErrorDuringMapping;
use CuyZ\Valinor\Mapper\Tree\Exception\UnresolvableShellType;
use CuyZ\Valinor\Mapper\Tree\RootNodeBuilder;
use CuyZ\Valinor\Type\Parser\TypeParser;
use CuyZ\Valinor\Type\Types\UnresolvableType;

/** @internal */
final class TypeTreeMapper implements TreeMapper
{
    public function __construct(
        private TypeParser $typeParser,
        private RootNodeBuilder $nodeBuilder,
    ) {}

    /** @pure */
    public function map(string $signature, mixed $source): mixed
    {
        $type = $this->typeParser->parse($signature);

        if ($type instanceof UnresolvableType) {
            throw new InvalidMappingTypeSignature($type);
        }

        try {
            $node = $this->nodeBuilder->build($source, $type);
        } catch (UnresolvableShellType $exception) {
            throw new TypeErrorDuringMapping($type, $exception);
        }

        if (! $node->isValid()) {
            throw new TypeTreeMapperError($source, $type->toString(), $node->messages());
        }

        return $node->value();
    }
}